// packageJ/eyeshield/eyeshieldIndex/eyeshieldIndex.js
const app = getApp();
let plugin = null;
try {
  plugin = requirePlugin("sdkPlugin").AiLink // 插件输出的页面加工函数 
} catch (error) {
  console.log(error)
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dtime: 0,
    devuceStatus: false,
    timeData: {},
    connected: false,
    explain_link: '',
    is_can: true,
    timeOut:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getData();
    this.getLimit();
  },
  toExplain() {
    if (!this.data.explain_link) {
      app.tips('未设置操作说明')
      return
    }
    wx.navigateTo({
      url: this.data.explain_link,
    })
  },
  equipment() {
    if(this.data.connected){
      wx.navigateTo({
        url: '/packageJ/eyeDevice/eyeDeviceMy/eyeDeviceMy?connected=' + this.data.connected,
      })
      return
    }
    wx.navigateTo({
      url: '/packageJ/eyeDevice/eyeDeviceMy/eyeDeviceMy',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  onChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onBLEConnectionStateChange();
    let basic_info = wx.getStorageSync('yz_basic_info');
    wx.setNavigationBarTitle({
      title: basic_info.home.mailInfo?.name || '',
    })
  },
  async openBtn() {
    await this.getLimit();
    if (!this.data.is_can) {
      app.tips('没有开启设备权限');
      return
    }
    // 没有设置就默认30分钟
    let dtime_set = this.data.dtime ? this.data.dtime : '1200000';
    this.data.timeOut = setTimeout(() => {
      this.closeBtn();
      this.data.timeOut = null;
      clearTimeout(this.data.timeOut);
    }, dtime_set);
    plugin.sendDataOfA7(['5', '1']);
    this.setData({
      devuceStatus: true
    })
    // 记录开始接口
    this.startEye();
  },
  closeBtn() {
    if (!this.data.connected) {
      app.tips('设备离线中')
      return
    }
    plugin.sendDataOfA7(['7', '1']);
    this.endEye();
    this.setData({
      devuceStatus: false
    })
  },
  startEye() {
    let urlStr = app.getNetAddresss("plugin.eye-device.frontend.modules.used.controllers.store.index");
    let sn = wx.getStorageSync('deviceId');
    let dtime = this.data.dtime?this.data.dtime:1800000;
    app._postNetWork({
      url: urlStr,
      data:{
        seconds:(dtime / 1000),
        device_sn:sn
      },
      success: (resdata) => {
        let res = resdata.data
        console.log(res);
      },
      fail: function (res) {}
    });
  },
  endEye() {
    let urlStr = app.getNetAddresss("plugin.eye-device.frontend.modules.used.controllers.store.confirm");
    let sn = wx.getStorageSync('deviceId');
    let endTime_minutes = this.data.timeData.minutes > 0?this.data.timeData.minutes * 60:0;
    let endTime_seconds = this.data.timeData.seconds > 1?this.data.timeData.seconds:0;
    let edntime = (endTime_minutes + endTime_seconds) * 1000;
    let dtime = this.data.dtime?this.data.dtime:1800000;

    console.log((dtime - edntime)/1000)
    app._postNetWork({
      url: urlStr,
      data:{
        seconds:(dtime - edntime)/1000,
        device_sn:sn
      },
      success: (resdata) => {
        let res = resdata.data
        console.log(res);
      },
      fail: function (res) {}
    });
  },
  changeTime(e) {
    let key = e.currentTarget.dataset.key;
    if (this.data.devuceStatus) {
      app.tips("设备正在运行中")
      return
    }
    if (key == "1") {
      // 增加倒计时 60000一分钟
      if (this.data.dtime >= 1800000) {
        app.tips('运行不能超过30分钟')
        return
      }
      this.setData({
        dtime: this.data.dtime + 300000
      })
    } else {
      if (this.data.dtime == 0) {
        app.tips('运行不能低于0分钟')
        return
      }
      this.setData({
        dtime: this.data.dtime - 300000
      })
    }
  },
  onBLEConnectionStateChange() {
    wx.onBLEConnectionStateChange((res) => {
      console.log('wx.onBLEConnectionStateChange() ', res.deviceId, res.connected, res.errorCode, res.errorMsg)
      // 该方法回调中可以用于处理连接意外断开等异常情况
      // console.log(`%c device ${res.deviceId} state has changed, connected: ${res.connected}`, 'color: #F26363')
      if (!res.connected) {
        wx.showToast({
          title: '连接已断开',
          icon: 'none'
        })
        this.setData({
          connected: false,
          devuceStatus: false
        })
        if (this.data.timeOut) {
          clearTimeout(this.data.timeOut)
        }
      } else {
        this.setData({
          connected: true,
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getData() {
    let urlStr = app.getNetAddresss("plugin.eye-device.frontend.controllers.page.index");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          this.setData({
            explain_link: res.data.explain_link
          })
        }
      },
      fail: function (res) {}
    });
  },
  getLimit() {
    let urlStr = app.getNetAddresss("plugin.eye-device.frontend.modules.device.controllers.limit.index");
    app._postNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          this.setData({
            is_can: res.data.is_can
          })
        }
      },
      fail: function (res) {}
    });
  },
})